package com.wontube.smr.web.controller;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.wontube.client.extension.remote.cache.ICacheHandler;
import com.wontube.client.extension.utils.RandomUtils;
import com.wontube.client.extension.utils.StringUtils;
import com.wontube.client.modle.vo.PagenateInfo;
import com.wontube.client.remote.Remoting;
import com.wontube.smr.web.client.IFeedbackHandler;
import com.wontube.smr.web.client.model.bo.KeyCode;
import com.wontube.smr.web.client.model.po.Feedback;
import com.wontube.smr.web.client.model.vo.FeedbackItems;
import com.wontube.smr.web.pub.WebConfig;
import com.wontube.web.ServiceResult;
import com.wontube.web.verify.KeyCodeImage;
import com.wontube.web.verify.VerifyResult;


/**
 * @author tanggf(2012-5-5)
 *
 */
@Controller
public class FeedbackController {
	private final static int PAGE_SIZE = 10;
	private final static String FEEDBACK_BUNDLE = "Feedback";
	private final static String feedback_verify_code_cache_name = "feedback_verify_code_";
	private final static int verify_code_ttl = 60 * 2;
	private final static int verify_code_tti = 60 * 2;
	
	@RequestMapping("/feedback")
	public void f1(HttpServletRequest request, 
			HttpServletResponse response) throws IOException{
		response.setStatus(HttpServletResponse.SC_MOVED_PERMANENTLY);
		response.sendRedirect(request.getContextPath() + "/feedback/");		
	}
	
	@RequestMapping("/feedback/")
	public ModelAndView feedbackHome(){
		return new ModelAndView("about/feedback/feedback_index");
	}
		
	/**
	 * list user feedbacks
	 * @param page
	 * @return
	 */
	@RequestMapping("/feedback/list")
	public ModelAndView list_feedbacks(@RequestParam(value="page", defaultValue="1") int page){		
		ModelAndView mv = new ModelAndView("about/feedback/feedback_list");
		Remoting<IFeedbackHandler> remoting = new Remoting<IFeedbackHandler>();
		IFeedbackHandler handler = remoting.createService(IFeedbackHandler.class);
		FeedbackItems items = handler.listFeedbacks(new PagenateInfo(page, PAGE_SIZE),0);//0表示美国版的feedback
		mv.addObject("feedbackItems", items);
		mv.addObject("page", page);
		return mv;
	}
	
	/**
	 * user post feedback
	 * @param feedback
	 * @param code
	 * @return
	 */
	@RequestMapping("/feedback/post")
	@ResponseBody
	public String post_feedback(Feedback feedback, KeyCode kc){		
		VerifyResult verify = feedback.verify();
		IFeedbackHandler handler = getHandler();
		if(verify.isDone() && checkCode(kc, verify, handler)){			
			Integer aff = handler.postFeedback(feedback);
			if(aff == null || aff.intValue() != 1){
				verify.addInvalidField("feedback.error.failToPost");
			}else{
				verify.setMessage("feedback.success.postFeedbackDone");
			}
		}
		
		return getServerResponseJsonString(verify);
	}
	
	private boolean checkCode(KeyCode kc, VerifyResult verify, IFeedbackHandler handler){	
		String code = getCacheHandler().<String>getUserCache(feedback_verify_code_cache_name, kc.getKey());
		boolean checked = false;
		if(code != null){
			if(code.equalsIgnoreCase(kc.getCode())){
				checked = true;
			}
		}
		
		if( ! checked){
			verify.addInvalidField("feedback.error.wrongVerifyCode");
		}
		return checked;
	}
	
	/**
	 * @param id
	 * @param response
	 * @throws IOException
	 */
	@RequestMapping("/feedback/verify_code")
	public void genFeedbackVerifyCodeImg(@RequestParam("key") String key, 
			HttpServletResponse response) throws IOException{
		if(StringUtils.isNullOrEmpty(key)){
			return;
		}		
		String code = RandomUtils.randomText(4);
		getCacheHandler().putUserCache(feedback_verify_code_cache_name, key, verify_code_ttl, verify_code_tti, code);
		
		String imageText = genImageText(code);
		response.setContentType("image/png");
		KeyCodeImage.outputImage(imageText, response.getOutputStream());
	}

	private String genImageText(String code) {
		StringBuilder sb = new StringBuilder();
		for (int i = 0; i < code.length(); i++) {
			sb.append(code.charAt(i)).append(" ");
		}
		return sb.toString();
	}
	
	/**
	 * @param id
	 * @param response
	 * @throws IOException
	 */
	@RequestMapping("/feedback/new_verify_code")
	public void genNewFeedbackVerifyCodeImg(@RequestParam("key") String key, 
			HttpServletResponse response) throws IOException{
		if(StringUtils.isNullOrEmpty(key)){
			return;
		}		
		genFeedbackVerifyCodeImg(key, response);
	}
	
	private String getServerResponseJsonString(VerifyResult verify){
		ServiceResult result = new ServiceResult(verify, FEEDBACK_BUNDLE, WebConfig.defaultLocale);		
		return result.toJsonString();
	}
	
	private IFeedbackHandler getHandler(){
		return new Remoting<IFeedbackHandler>().createService(IFeedbackHandler.class);
	}
	
	private ICacheHandler getCacheHandler(){
		Remoting<ICacheHandler> remoting = new Remoting<ICacheHandler>();
		remoting.setDataFormat(Remoting.dataFormatHessian);
		return remoting.createService(ICacheHandler.class);
	}
}
